/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from 'react';
import { Avatar, Button, Col, Form, Input, Row, message } from 'antd';
import {
  UserOutlined,
  LockOutlined,
  MobileOutlined,
  MailOutlined,
} from '@ant-design/icons';
import logo from '/logo.svg';
import { useHistory } from 'react-router';
import createAccount from '@src/apis/create_account';
import omit from 'lodash/omit';
import { IRegisterInfo } from '@src/types/account';
import { delay, validatePhoneNumber } from '@src/utils';
import { useSendSmsCode } from '@src/hooks';
import { opType } from '@src/const';
import { useUserInfo } from '@src/store/user/hooks';

const App: React.FC = () => {
  const [form] = Form.useForm();
  const history = useHistory();
  const userInfo = useUserInfo();
  const [submitBtnloading, setSubmitBtnLoading] = useState(false);
  const {
    countdown,
    loading: codeBtnLoading,
    handleSendSmsCode,
  } = useSendSmsCode();

  // 登录过的直接返回
  useEffect(() => {
    if (userInfo.uid) {
      history.goBack();
    }
  }, [userInfo.uid]);

  const verifyMobile = (rule, val, callback) => {
    // 验证手机号
    if (!val) {
      callback();
    }
    const validateResult = validatePhoneNumber(val); // 自定义规则
    if (!validateResult) {
      callback('不合法的手机号!');
      return;
    }
    callback();
  };

  const verifyCode = (rule, val, callback) => {
    // 验证验证码
    if (!val) {
      callback();
    }
    const myReg = /^[0-9]{6}$/;
    const validateResult = myReg.test(val);
    if (!validateResult) {
      callback('验证码为六位数！');
      return;
    }
    callback();
  };

  const goToLogin = () => {
    history.push('/login');
  };

  // 提交
  const submit = async (
    values: IRegisterInfo & { repeatePassword: string },
  ) => {
    if (values.repeatePassword !== values.password) {
      message.error('两次输入的密码不一致');
      return;
    }

    setSubmitBtnLoading(true);

    try {
      const res = await createAccount(omit(values, ['repeatePassword']));
      if (res.uid) {
        message.success('注册成功，即将跳往登录');
        await delay(1500);
        goToLogin();
      }
    } catch (error: any) {
      message.error(error.msg); // 这里后续搞一个统一的错误处理
    } finally {
      setSubmitBtnLoading(false);
    }
  };

  return (
    <div className='h-full w-full bg-login-bg flex justify-center items-center text-[14px]'>
      <div className='w-[328px] h-auto'>
        <div style={{ textAlign: 'center' }}>
          <div className='flex pt-[20px] justify-center items-center'>
            <Avatar src={logo} />
            <span
              style={{
                lineHeight: '44px',
                fontSize: '33px',
                fontWeight: '600px',
              }}>
              smart AI
            </span>
          </div>
          <div className='my-8 text-gray-500'>做最懂您的智能助手</div>
        </div>
        <Form
          form={form}
          name='normal_login'
          className='login-form'
          onFinish={submit}>
          <Form.Item
            name='username'
            rules={[
              {
                required: true,
                message: '用户名是必填项!',
              },
            ]}>
            <Input
              allowClear
              size='large'
              prefix={
                <UserOutlined
                  className='site-form-item-icon'
                  style={{ color: '#1890ff' }}
                />
              }
              placeholder='请输入用户名'
            />
          </Form.Item>
          <Form.Item
            name='password'
            rules={[
              {
                required: true,
                message: '密码是必填项!',
              },
            ]}>
            <Input.Password
              size='large'
              prefix={
                <LockOutlined
                  className='site-form-item-icon'
                  style={{ color: '#1890ff' }}
                />
              }
              type='password'
              placeholder='请输入密码'
            />
          </Form.Item>
          <Form.Item
            name='repeatePassword'
            rules={[
              {
                required: true,
                message: '二次输入密码是必填项!',
              },
              {
                validator: (rule, val, callback) => {
                  const { password = '' } = form.getFieldsValue();
                  if (val && password !== val) {
                    callback('两次输入的密码不一致!');
                    return;
                  }
                  callback();
                },
                message: '两次输入的密码不一致!',
              },
            ]}>
            <Input.Password
              size='large'
              prefix={
                <LockOutlined
                  className='site-form-item-icon'
                  style={{ color: '#1890ff' }}
                />
              }
              type='password'
              placeholder='请再次输入密码'
            />
          </Form.Item>
          <Form.Item
            name='phoneNumber'
            rules={[
              {
                required: true,
                message: '手机号是必填项!',
              },
              {
                validator: verifyMobile,
                message: '不合法的手机号!',
              },
            ]}>
            <Input
              allowClear
              size='large'
              prefix={
                <MobileOutlined
                  className='site-form-item-icon'
                  style={{ color: '#1890ff' }}
                />
              }
              placeholder='请输入手机号!'
            />
          </Form.Item>
          <Row style={{ width: '100%' }}>
            <Col flex='2 1' style={{ margin: '0px 8px 0px 0px' }}>
              <Form.Item
                name='code'
                rules={[
                  {
                    required: true,
                    message: '验证码是必填项!',
                  },
                  {
                    validator: verifyCode,
                    message: '验证码是六位数！',
                  },
                ]}>
                <Input
                  size='large'
                  prefix={
                    <MailOutlined
                      className='site-form-item-icon'
                      style={{ color: '#1890ff' }}
                    />
                  }
                  placeholder='请输入验证码!'></Input>
              </Form.Item>
            </Col>
            <Col flex='1 2' style={{ float: 'right', marginBottom: '24px' }}>
              <Button
                disabled={!!countdown}
                size='large'
                loading={codeBtnLoading}
                onClick={() =>
                  handleSendSmsCode(
                    form.getFieldsValue().phoneNumber,
                    opType.register,
                  )
                }>
                {countdown ? `${countdown}秒后重新获取` : '获取验证码'}
              </Button>
            </Col>
          </Row>
          <div>
            <Form.Item>
              <Button
                type='link'
                style={{ float: 'right' }}
                onClick={goToLogin}>
                已有账号？立即登录
              </Button>
            </Form.Item>
          </div>
          <Form.Item>
            <Button
              type='primary'
              htmlType='submit'
              className='login-form-button'
              style={{ width: '100%' }}
              loading={submitBtnloading}
              size='large'>
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default App;
